package com.mvp.shq.washer.ui.shop.order.ordersubmit;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jaeger.library.StatusBarUtil;
import com.mvp.shq.washer.R;
import com.mvp.shq.washer.adapter.OrderAllListAdapter;
import com.mvp.shq.washer.adapter.OrderListAdapter;
import com.mvp.shq.washer.adapter.ShopAddressAdapter;
import com.mvp.shq.washer.base.BaseActivity;
import com.mvp.shq.washer.entity.result.BaseResult;
import com.mvp.shq.washer.entity.shop.AddressData;
import com.mvp.shq.washer.entity.shop.Product;
import com.mvp.shq.washer.entity.shop.ProductUnit;
import com.mvp.shq.washer.entity.shop.TotalOrderData;
import com.mvp.shq.washer.entity.shop.TotalOrderList;
import com.mvp.shq.washer.entity.shop.TotalOrderListData;
import com.mvp.shq.washer.entity.shop.result.OrderDataResult;
import com.mvp.shq.washer.entity.shop.result.OrderResult;
import com.mvp.shq.washer.entity.shop.result.ProductResult;
import com.mvp.shq.washer.rxbus.RxBus;
import com.mvp.shq.washer.rxbus.Subscribe;
import com.mvp.shq.washer.utils.DBUtil;
import com.mvp.shq.washer.utils.DataDictionary;
import com.mvp.shq.washer.utils.EventCode;
import com.mvp.shq.washer.utils.JumpUtil;
import com.mvp.shq.washer.utils.RecyclerViewDivider;
import com.mvp.shq.washer.utils.SpUtil;
import com.mvp.shq.washer.utils.StringUtils;
import com.orhanobut.logger.Logger;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;

/**
 * Created by westing on 2017/10/11.
 * 订单提交
 */
public class

OrderSumbitActivity extends BaseActivity<Presenter, Model> implements OrderSumbitConstract.View {
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.address_person)
    TextView addressPerson;//收件人
    @BindView(R.id.address_phone)
    TextView addressPhone;//收件电话
    @BindView(R.id.tv_address)
    TextView tvAddress;//收件地址
    @BindView(R.id.lin_address)
    LinearLayout linAddress;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    //底部布局
    @BindView(R.id.radio_ni)
    CheckBox radioNi;//匿名选择
    @BindView(R.id.tv_money_fu1)
    TextView tvMoneyFu1;//支付金额元
    @BindView(R.id.tv_money_fu2)
    TextView tvMoneyFu2;//支付金额角分
    @BindView(R.id.tv_fu_add)
    TextView tvFuAdd;//加号
    @BindView(R.id.tv_fu_ji)
    TextView tvFuJi;//积分
    @BindView(R.id.bnt_submit)
    Button bntSubmit;
    @BindView(R.id.tv_jifen)
    TextView tvJifen;

    private List<TotalOrderListData> mTotalOrderList;//商品信息
    private AddressData mAddressData;//地址资料
    private TotalOrderData mTotalOrder;//订单提交
    @Override
    public int getLayoutId() {
        return R.layout.activity_ordersubmit;
    }

    @Override
    public void initView() {
        StatusBarUtil.setColor(this, ContextCompat.getColor(context, R.color.money), 9);
        title.setText("提交订单");
        recyclerview.setLayoutManager(new LinearLayoutManager(context));
        RecyclerViewDivider divider = new RecyclerViewDivider(context, LinearLayoutManager.HORIZONTAL, 10, ContextCompat.getColor(context, R.color.gregf8));
        recyclerview.addItemDecoration(divider);

        Intent intent=getIntent();
        if(intent!=null){
            int pageType=intent.getIntExtra("pageType",0);
            if(pageType==EventCode.SHOP_PAGETYPE_0){
                //商品详情
                RxBus.get().send(EventCode.SHOP_SEND_PRODUCT_ON_PRODUCT_DETAIL);
                Logger.d("请求SHOP_SEND_PRODUCT_ON_PRODUCT_DETAIL---");
            }else if (pageType==EventCode.SHOP_PAGETYPE_1){
                //购物车
                RxBus.get().send(EventCode.SHOP_SEND_PRODUCT_ON_SHOPCAR);
                Logger.d("请求SHOP_SEND_PRODUCT_ON_SHOPCAR 0000---");
            }
        }


    }
    private double cashPrice=0;
    private double integralPrice=0,totalPrice=0;
    private String payMode;
    private void initData() {

        for (int i=0,len=mTotalOrderList.size();i<len;i++){

            List<ProductUnit> ecProductUnitDtoList=new ArrayList<>();
            for (int j=0,lens=mTotalOrderList.get(i).getProducts().size();j<lens;j++){
                Product product= mTotalOrderList.get(i).getProducts().get(j);
                ecProductUnitDtoList.add(new ProductUnit(product.getByNum(),product.getId()));
                cashPrice += product.getCashPrice()*product.getByNum();
                integralPrice += product.getIntegralPrice()*product.getByNum();
            }
            if(integralPrice==0){
                payMode= DataDictionary.PAY_MODE_CASH;
            }else if(cashPrice==0&&integralPrice!=0){
                payMode= DataDictionary.PAY_MODE_INTEGRAL;
            }else
            {
                payMode= DataDictionary.PAY_MODE_CASH_AND_INTEGRAL;
            }
            mTotalOrderList.get(i).setPayMode(payMode);
            mTotalOrderList.get(i).setEcProductUnitDtoList(ecProductUnitDtoList);
        }
        totalPrice=cashPrice;
        if(integralPrice==0)
        {
            tvFuJi.setVisibility(View.GONE);
            tvFuAdd.setVisibility(View.GONE);
            tvJifen.setVisibility(View.GONE);
        }else if(cashPrice==0&&integralPrice!=0){
            tvMoneyFu1.setVisibility(View.GONE);
            tvMoneyFu2.setVisibility(View.GONE);
            tvFuAdd.setVisibility(View.GONE);

        }
        tvMoneyFu1.setText((int)cashPrice+"");
        tvMoneyFu2.setText(StringUtils.BigDecimalToStr(BigDecimal.valueOf(cashPrice)));
        tvFuJi.setText((int)integralPrice+"");

    }

    @Subscribe(code = EventCode.SHOP_SUMBIT_ORDER)
    public void getProductList(TotalOrderList totalOrderList){
        List<TotalOrderListData> totalOrderListData=totalOrderList.getProductResultList();
        if(totalOrderListData==null)return;
        this.mTotalOrderList=totalOrderListData;
        initData();
        OrderAllListAdapter listadapter = new OrderAllListAdapter(context,mTotalOrderList);
        recyclerview.setAdapter(listadapter);
        //获取默认地址
        presenter.getDefAddress();
    }

    @OnClick({R.id.back, R.id.lin_address, R.id.bnt_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.lin_address:
                //地址选择
                JumpUtil.toShopAddress(context, ShopAddressAdapter.TYPE_CHOOSE);
                break;
            case R.id.bnt_submit:
                createMyOrder();
                break;
        }
    }
    @Subscribe(code = EventCode.SHOP_CHOOSE_ADDRESS)
    public void updateAddress(AddressData addressData){
        getDefaultAddress(addressData);
    }

    private void createMyOrder() {
        if(mTotalOrder==null) {
            return;
        }
        showLoadingDialog(true);

        presenter.createOrder(mTotalOrder);
    }


    @Override
    public void getDefaultAddress(AddressData addressData) {
        if(addressData==null)return;
        mAddressData=addressData;
        addressPerson.setText(""+addressData.getReceiverName());//收件人
        addressPhone.setText(""+addressData.getReceiverPhone());//收件电话
        tvAddress.setText(addressData.getProvinceName()+addressData.getCityName()+addressData.getAreaName()+addressData.getDetailAddress());//收件地址
//        SpUtil.setAddressData(addressData);

        String userId = SpUtil.getUser().getId();
        String addressDesc=mAddressData.getProvinceName()+mAddressData.getCityName()+mAddressData.getAreaName()+mAddressData.getDetailAddress();
        String isMultiple="0";
        if(mTotalOrderList.size()>0){
            isMultiple="1";
        }
        mTotalOrder=new TotalOrderData(
                addressDesc,
                mAddressData.getAreaId(),
                cashPrice,
                mAddressData.getCityId(),
                mTotalOrderList,
                integralPrice,
                isMultiple,
                "",
                mAddressData.getProvinceId(),
                totalPrice,
                mAddressData.getUnitId(),
                userId,
                mAddressData.getReceiverPhone(),
                mAddressData.getReceiverName());
    }
    private OrderDataResult mOorderResult;
    @Override
    public void createOrder(OrderDataResult orderResult) {
        Logger.d("创建订单成功："+orderResult);
        mOorderResult = orderResult;
        //删除购物车数据
        List<String> produtIds = new ArrayList<>();
        List<TotalOrderListData> ecOrderDtoList = mTotalOrder.getEcOrderDtoList();
        for (int i=0;i<ecOrderDtoList.size();i++){
            List<ProductUnit> ecProductUnitDtoList = ecOrderDtoList.get(i).getEcProductUnitDtoList();
            for (int j=0;j<ecProductUnitDtoList.size();j++){
                produtIds.add(ecProductUnitDtoList.get(j).getProductUnitId());
            }
        }
        DBUtil.getInstance().delProductById(produtIds);
        JumpUtil.toOrderPay(context,1,mOorderResult.getId());
        finish();
    }
    @Subscribe(code = EventCode.SHOP_ORDER_GET_ORDER)
    public void sendOrderResult(){
        RxBus.get().send(EventCode.SHOP_ORDER_SEND_ORDER,mOorderResult);
    }

    @Subscribe(code = EventCode.SHOP_PAY_SUCCESS)
    public void paySuccess(){
        finish();
    }
}
